package com.ynkbny.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynkbny.domain.dto.TEpUploadTimeDTO;
import com.ynkbny.mapper.TEpUploadTimeMapper;
import com.ynkbny.service.TEpUploadTimeService;
import com.ynkbny.service.outsideinterface.MyClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
* @author YY
* @description 针对表【t_ep_upload_time(企业上传数据时间表)】的数据库操作Service实现
* @createDate 2023-07-17 16:49:56
*/
@Slf4j
@Service
public class TEpUploadTimeServiceImpl extends ServiceImpl<TEpUploadTimeMapper, TEpUploadTimeDTO>
    implements TEpUploadTimeService{

    @Resource
    private MyClient myClient;

    @Resource
    private TEpUploadTimeDTO uploadTimeDTO;

    /**
     * 更新token
     * @return ture or false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateToken(String enterpriseCode, String password) {
        // 接口调用成功返回编码
        String success = "200";

        JSONObject getAKResult = myClient.getAK(enterpriseCode,password);
        String responseCode = getAKResult.getString("responseCode");
        if (!success.equals(responseCode)){
            log.info("获取token失败:{}", getAKResult.toJSONString());
            return false;
        }
        String token = getAKResult.getJSONObject("data").getString("token");
        // 获取能耗数据交换时间段，格式：时:分:秒
        String timeStr = getAKResult.getJSONObject("data").getString("enterpriseUploadTime");
        // 格式化时间
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        String[] split = timeStr.split("-");
        Time sTime = null;
        Time eTime = null;
        try {
            sTime = new Time(format.parse(split[0]).getTime());
            eTime = new Time(format.parse(split[1]).getTime());
        } catch (ParseException e) {
            log.info("日期格式化异常：{}", e.toString());
        }

        // 更新时间
        uploadTimeDTO.setEnterpriseCode(enterpriseCode);
        uploadTimeDTO.setToken(token);
        uploadTimeDTO.setStartTime(sTime);
        uploadTimeDTO.setEndTime(eTime);
        log.info("获取token：{}",token);
        boolean update = this.saveOrUpdate(uploadTimeDTO);
        return update;
    }

    /**
     * 获取t_ep_upload_time表中的token（当前时间在数据交换时间内的）
     * 查询条件 1.统一社会信用代码等于入参 2.token不为null 3.当前时间在开始时间和结束时间之间
     * @param enterpriseCode  统一社会信用代码
     * @return token
     */
    @Override
    public String getTokenForDataBase(String enterpriseCode) {
        DateTime now = DateTime.now();
        long time = now.getTime();
        Time nowTime = new Time(time);
        LambdaQueryWrapper<TEpUploadTimeDTO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TEpUploadTimeDTO::getEnterpriseCode,enterpriseCode)
                .isNotNull(TEpUploadTimeDTO::getToken)
                .le(TEpUploadTimeDTO::getStartTime,nowTime)
                .gt(TEpUploadTimeDTO::getEndTime,nowTime);
        TEpUploadTimeDTO dto = this.getOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(dto)) {
            return "";
        }
        return dto.getToken();
    }

    /**
     * 获取t_ep_upload_time表中的token
     * @param enterpriseCode  统一社会信用代码
     * @return token
     */
    @Override
    public String getToken(String enterpriseCode) {
        LambdaQueryWrapper<TEpUploadTimeDTO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TEpUploadTimeDTO::getEnterpriseCode,enterpriseCode)
                .isNotNull(TEpUploadTimeDTO::getToken);
        TEpUploadTimeDTO dto = this.getOne(lambdaQueryWrapper);

        if (ObjectUtils.isEmpty(dto)){
            return "";
        }
        return dto.getToken();
    }
}




